package com.tools.compass.location;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class LocationMe extends Activity {
	TextView mTextView;
	Button mButton;
	TelephonyManager tm;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mTextView = (TextView) findViewById(R.id.TextView01);
		mButton = (Button) findViewById(R.id.Button01);
		tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);

		mButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
				int cid = gcl.getCid();
				int lac = gcl.getLac();

				int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0,
						3));
				int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3,
						5));
				try {
					// 组装JSON查询字符串
					JSONObject holder = new JSONObject();
					holder.put("version", "1.1.0");
					holder.put("host", "maps.google.com");
					holder.put("address_language", "zh_CN");
					holder.put("request_address", true);

					JSONArray array = new JSONArray();
					JSONObject data = new JSONObject();
					data.put("cell_id", cid); // 25070
					data.put("location_area_code", lac);// 4474
					data.put("mobile_country_code", mcc);// 460
					data.put("mobile_network_code", mnc);// 0
					array.put(data);
					holder.put("cell_towers", array);

					// 创建连接，发送请求并接受回应
					DefaultHttpClient client = new DefaultHttpClient();

					HttpPost post = new HttpPost(
							"http://www.google.com/loc/json");

					StringEntity se = new StringEntity(holder.toString());

					post.setEntity(se);
					HttpResponse resp = client.execute(post);

					HttpEntity entity = resp.getEntity();

					BufferedReader br = new BufferedReader(
							new InputStreamReader(entity.getContent()));
					StringBuffer sb = new StringBuffer();
					String result = br.readLine();

					while (result != null) {

						sb.append(result);
						result = br.readLine();
					}

//					mTextView.setText(sb.toString());

					JSONObject jsonObject = new JSONObject(sb.toString());
					JSONObject subjosn = new JSONObject(jsonObject
							.getString("location"));
//					getLocalByItude(subjosn.getString("latitude"), subjosn
//							.getString("longitude"));
					
					getLocation(subjosn.getString("latitude"), subjosn
							.getString("longitude"));
				} catch (Exception e) {
					// TODO: handle exception
				}

			}

		});
	}

	// 通过经纬度获取地理信息
	private void getLocalByItude(String latitude, String longitude) {
		HttpURLConnection conn = null;
		String line = null;
		try {

			URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q="
					+ latitude + "," + longitude);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			// conn.setConnectTimeout(timeoutConnection);
			// conn.setReadTimeout(timeoutSocket);
			conn.setRequestMethod("GET");
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufReader = new BufferedReader(inStreamReader);
			StringBuffer bufStr = new StringBuffer();

			while ((line = bufReader.readLine()) != null) {
				bufStr.append(line);
			}
			line = bufStr.toString();
			if (line != null && line.length() > 0) {
				JSONObject jsonobject = new JSONObject(line);
				JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
						.toString());
				line = "";
				for (int i = 0; i < jsonArray.length(); i++) {
					line = jsonArray.getJSONObject(i).getString("address");
				}

				System.out.println(line);
				Log.d("line", line);
				// 回调
				// mLocalOkListener.onGetOk(line);

			}
		} catch (Exception e) {
			// TODO: handle exception
			// mLocalOkListener.onGetOk("");
		} finally {
			if (conn != null) {
				conn.disconnect();
				// mLocalOkListener.onGetOk(line);
			}
		}
	}

	private String getLocation(String latitude, String longitude)
			throws Exception {
		String resultString = "";

		/** 这里采用get方法，直接将参数加到URL上 */
		String urlString = String.format(
				"http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", latitude,
				longitude);
		Log.i("URL", urlString);

		/** 新建HttpClient */
		HttpClient client = new DefaultHttpClient();
		/** 采用GET方法 */
		HttpGet get = new HttpGet(urlString);
		try {
			/** 发起GET请求并获得返回数据 */
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			BufferedReader buffReader = new BufferedReader(
					new InputStreamReader(entity.getContent()));
			StringBuffer strBuff = new StringBuffer();
			String result = null;
			while ((result = buffReader.readLine()) != null) {
				strBuff.append(result);
			}
			resultString = strBuff.toString();
//			04-23 10:30:09.975: INFO/URL(3011): http://maps.google.cn/maps/geo?key=abcdefg&q=39.9366851,116.2686759

			/** 解析JSON数据，获得物理地址 */
			if (resultString != null && resultString.length() > 0) {
				JSONObject jsonobject = new JSONObject(resultString);
				JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
						.toString());
				resultString = "";
				for (int i = 0; i < jsonArray.length(); i++) {
					resultString = jsonArray.getJSONObject(i).getString(
							"address");
				}
				System.out.println(resultString);
				mTextView.setText(resultString);
			}
		} catch (Exception e) {
			throw new Exception("获取物理位置出现错误:" + e.getMessage());
		} finally {
			get.abort();
			client = null;
		}

		return resultString;
	}

}